package com.my.ads.lib.activity;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.support.design.widget.TabLayout;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.widget.RelativeLayout;

import com.my.ads.lib.AdSummary;
import com.my.ads.lib.bean.AdapterViewPager;
import com.my.ads.lib.bean.ParseResult;
import com.my.ads.lib.bean.RecyclerAdapterWeather;
import com.my.ads.lib.bean.WeatherBean;
import com.my.ads.lib.bean.WeatherFragmentRecyclerView;
import com.rapid.clean.deep.R;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by xuanyang on 2018/3/6.
 */

public class WeatherActivity extends FragmentActivity {
    private Handler handler = new Handler();
    private InputStream mInputStream = null;
    private HttpClient mHttpClient = null;
    private static Map<String, Integer> speedUnits = new HashMap<>(3);
    private static Map<String, Integer> pressUnits = new HashMap<>(3);
    private static boolean mappingsInitialised = false;
    ProgressDialog progressDialog;
    public String recentCity = "";
    ViewPager viewPager;
    TabLayout tabLayout;
    private List<WeatherBean> longTermWeather = new ArrayList<>();
    private List<WeatherBean> longTermTodayWeather = new ArrayList<>();
    private List<WeatherBean> longTermTomorrowWeather = new ArrayList<>();
    private LocationManager locationManager;
    private String locationProvider;
    private String lat = "35";
    private String lon = "139";
    private RelativeLayout weather_ad;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.weather_activity_scrolling);
        initMappings();
        progressDialog = new ProgressDialog(WeatherActivity.this);
        viewPager = (ViewPager) findViewById(R.id.viewPager);
        tabLayout = (TabLayout) findViewById(R.id.tabs);
        weather_ad = (RelativeLayout) findViewById(R.id.weather_ad);


        new Handler().postDelayed(new Runnable() {
            public void run() {
                AdSummary.getInstance().showInterstitialAd(WeatherActivity.this, 0, "");
            }
        }, 500);

        try {
            AdSummary.getInstance().showNativeAd(this, weather_ad, false);
        } catch (Exception e) {
            e.printStackTrace();
        }


        //获取地理位置管理器
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        if (locationManager != null) {
            //获取所有可用的位置提供器
            List<String> providers = locationManager.getProviders(true);
            if (providers.contains(LocationManager.GPS_PROVIDER)) {
                //如果是GPS
                locationProvider = LocationManager.GPS_PROVIDER;
            } else if (providers.contains(LocationManager.NETWORK_PROVIDER)) {
                //如果是Network
                locationProvider = LocationManager.NETWORK_PROVIDER;
            } else {
                updateLongTermWeatherUI();
                return;
            }
            //获取Location
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                // TODO: Consider calling
                updateLongTermWeatherUI();
                return;
            }
            Location location = locationManager.getLastKnownLocation(locationProvider);
            if (location != null) {
                //不为空,显示地理位置经纬度
                lat = String.valueOf(location.getLatitude());
                lon = String.valueOf(location.getLongitude());
//                String locationStr = "维度：" + location.getLatitude() + "\n"
//                        + "经度：" + location.getLongitude();
//                Log.d("TAGGG", locationStr);

            }
            //监视地理位置变化
            locationManager.requestLocationUpdates(locationProvider, 3000, 1, locationListener);
            SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(WeatherActivity.this);
            String lastLongterm = sp.getString("lastLongterm", "");
            Long lasttime = sp.getLong("lasttime", 0l);
            if (lastLongterm.isEmpty()) {
                mShare();
            } else if ((System.currentTimeMillis() - lasttime) > 1000 * 60 * 60 * 24 * 5) {
                mShare();
            } else {
                parseLongTermJson(lastLongterm);
            }
        }
        updateLongTermWeatherUI();


    }

    LocationListener locationListener = new LocationListener() {

        @Override
        public void onStatusChanged(String provider, int status, Bundle arg2) {

        }

        @Override
        public void onProviderEnabled(String provider) {

        }

        @Override
        public void onProviderDisabled(String provider) {

        }

        @Override
        public void onLocationChanged(Location location) {
            //如果位置发生变化,重新显示

        }
    };

    private void updateLongTermWeatherUI() {

        AdapterViewPager viewPagerAdapter = new AdapterViewPager(getSupportFragmentManager());

        Bundle bundleToday = new Bundle();
        bundleToday.putInt("day", 0);
        WeatherFragmentRecyclerView recyclerViewFragmentToday = new WeatherFragmentRecyclerView();
        recyclerViewFragmentToday.setArguments(bundleToday);
        viewPagerAdapter.addFragment(recyclerViewFragmentToday, getString(R.string.today));

        Bundle bundleTomorrow = new Bundle();
        bundleTomorrow.putInt("day", 1);
        WeatherFragmentRecyclerView recyclerViewFragmentTomorrow = new WeatherFragmentRecyclerView();
        recyclerViewFragmentTomorrow.setArguments(bundleTomorrow);
        viewPagerAdapter.addFragment(recyclerViewFragmentTomorrow, getString(R.string.tomorrow));

        Bundle bundle = new Bundle();
        bundle.putInt("day", 2);
        WeatherFragmentRecyclerView recyclerViewFragment = new WeatherFragmentRecyclerView();
        recyclerViewFragment.setArguments(bundle);
        viewPagerAdapter.addFragment(recyclerViewFragment, getString(R.string.later));

        int currentPage = viewPager.getCurrentItem();

        viewPagerAdapter.notifyDataSetChanged();
        viewPager.setAdapter(viewPagerAdapter);
        tabLayout.setupWithViewPager(viewPager);
        viewPager.setCurrentItem(currentPage, false);
    }

    public ParseResult parseLongTermJson(String result) {
        int i;
        try {
            JSONObject reader = new JSONObject(result);

            final String code = reader.optString("cod");
            if ("404".equals(code)) {
                if (longTermWeather == null) {
                    longTermWeather = new ArrayList<>();
                    longTermTodayWeather = new ArrayList<>();
                    longTermTomorrowWeather = new ArrayList<>();
                }
                return ParseResult.CITY_NOT_FOUND;
            }

            longTermWeather = new ArrayList<>();
            longTermTodayWeather = new ArrayList<>();
            longTermTomorrowWeather = new ArrayList<>();

            JSONArray list = reader.getJSONArray("list");
            for (i = 0; i < list.length(); i++) {
                WeatherBean weather = new WeatherBean();

                JSONObject listItem = list.getJSONObject(i);
                JSONObject main = listItem.getJSONObject("main");

                weather.setDate(listItem.getString("dt"));
                weather.setTemperature(main.getString("temp"));

                weather.setDescription(listItem.optJSONArray("weather").getJSONObject(0).getString("description"));
                JSONObject windObj = listItem.optJSONObject("wind");
                if (windObj != null) {
                    weather.setWind(windObj.getString("speed"));
                    weather.setWindDirectionDegree(windObj.getDouble("deg"));
                }
                weather.setPressure(main.getString("pressure"));
                weather.setHumidity(main.getString("humidity"));

                JSONObject rainObj = listItem.optJSONObject("rain");
                String rain = "";

                if (rainObj != null) {
                    rain = getRainString(rainObj);
                } else {
                    JSONObject snowObj = listItem.optJSONObject("snow");
                    if (snowObj != null) {
                        rain = getRainString(snowObj);
                    } else {
                        rain = "0";
                    }
                }
                weather.setRain(rain);

                final String idString = listItem.optJSONArray("weather").getJSONObject(0).getString("id");
                weather.setId(idString);


                final String dateMsString = listItem.getString("dt") + "000";
                Calendar cal = Calendar.getInstance();
                cal.setTimeInMillis(Long.parseLong(dateMsString));

                weather.setIcon(setWeatherIcon(Integer.parseInt(idString), cal.get(Calendar.HOUR_OF_DAY)));
//                longTermTodayWeather.add(weather);
                Calendar today = Calendar.getInstance();
                if (cal.get(Calendar.DAY_OF_YEAR) == today.get(Calendar.DAY_OF_YEAR)) {
                    longTermTodayWeather.add(weather);
                } else if (Integer.valueOf(cal.get(Calendar.DAY_OF_YEAR)) == today.get(Calendar.DAY_OF_YEAR) + 1) {
                    longTermTomorrowWeather.add(weather);
                } else {
                    longTermWeather.add(weather);
                }
            }
            new Thread() {
                @Override
                public void run() {//在run()方法实现业务逻辑；
                    //更新UI操作；
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            updateLongTermWeatherUI();
                        }
                    });

                }
            }.start();
            SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(WeatherActivity.this).edit();
            editor.putString("lastLongterm", result);
            editor.putLong("lasttime", System.currentTimeMillis());
            editor.commit();
        } catch (JSONException e) {
            e.printStackTrace();
            return ParseResult.JSON_EXCEPTION;
        }

        return ParseResult.OK;
    }

    public static String getRainString(JSONObject rainObj) {
        String rain = "0";
        if (rainObj != null) {
            rain = rainObj.optString("3h", "fail");
            if ("fail".equals(rain)) {
                rain = rainObj.optString("1h", "0");
            }
        }
        return rain;
    }

    private String setWeatherIcon(int actualId, int hourOfDay) {
        int id = actualId / 100;
        String icon = "";
        if (actualId == 800) {
            if (hourOfDay >= 7 && hourOfDay < 20) {
                icon = this.getString(R.string.weather_sunny);
            } else {
                icon = this.getString(R.string.weather_clear_night);
            }
        } else {
            switch (id) {
                case 2:
                    icon = this.getString(R.string.weather_thunder);
                    break;
                case 3:
                    icon = this.getString(R.string.weather_drizzle);
                    break;
                case 7:
                    icon = this.getString(R.string.weather_foggy);
                    break;
                case 8:
                    icon = this.getString(R.string.weather_cloudy);
                    break;
                case 6:
                    icon = this.getString(R.string.weather_snowy);
                    break;
                case 5:
                    icon = this.getString(R.string.weather_rainy);
                    break;
            }
        }
        return icon;
    }

    public static long saveLastUpdateTime(SharedPreferences sp) {
        Calendar now = Calendar.getInstance();
        sp.edit().putLong("lastUpdate", now.getTimeInMillis()).apply();
        return now.getTimeInMillis();
    }

    public RecyclerAdapterWeather getAdapter(int id) {
        RecyclerAdapterWeather weatherRecyclerAdapter;
        if (id == 0) {
            weatherRecyclerAdapter = new RecyclerAdapterWeather(this, longTermTodayWeather);
        } else if (id == 1) {
            weatherRecyclerAdapter = new RecyclerAdapterWeather(this, longTermTomorrowWeather);
        } else {
            weatherRecyclerAdapter = new RecyclerAdapterWeather(this, longTermWeather);
        }
        return weatherRecyclerAdapter;
    }

    public static String getWindDirectionString(SharedPreferences sp, Context context, WeatherBean weather) {
        try {
            if (Double.parseDouble(weather.getWind()) != 0) {
                String pref = sp.getString("windDirectionFormat", null);
                if ("arrow".equals(pref)) {
                    return weather.getWindDirection(8).getArrow(context);
                } else if ("abbr".equals(pref)) {
                    return weather.getWindDirection().getLocalizedString(context);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return "";
    }

    public static void initMappings() {
        if (mappingsInitialised)
            return;
        mappingsInitialised = true;
        speedUnits.put("m/s", R.string.speed_unit_mps);
        speedUnits.put("kph", R.string.speed_unit_kph);
        speedUnits.put("mph", R.string.speed_unit_mph);
        speedUnits.put("kn", R.string.speed_unit_kn);

        pressUnits.put("hPa", R.string.pressure_unit_hpa);
        pressUnits.put("kPa", R.string.pressure_unit_kpa);
        pressUnits.put("mm Hg", R.string.pressure_unit_mmhg);
    }

    public static String localize(SharedPreferences sp, Context context, String preferenceKey, String defaultValueKey) {
        String preferenceValue = sp.getString(preferenceKey, defaultValueKey);
        String result = preferenceValue;
        if ("speedUnit".equals(preferenceKey)) {
            if (speedUnits.containsKey(preferenceValue)) {
                result = context.getString(speedUnits.get(preferenceValue));
            }
        } else if ("pressureUnit".equals(preferenceKey)) {
            if (pressUnits.containsKey(preferenceValue)) {
                result = context.getString(pressUnits.get(preferenceValue));
            }
        }
        return result;
    }

    public void mShare() {
        new Thread() {
            @Override
            public void run() {
                super.run();
                try {
                    mHttpClient = new DefaultHttpClient();
                    HttpParams params = mHttpClient.getParams();
                    String loginUrl = "http://api.openweathermap.org/data/2.5/forecast?lat=" + lat + "&lon=" + lon + "&appid=614d8aa41fd3a436a19a6ee6adc5b6f9";

                    HttpPost post = new HttpPost(loginUrl);
                    HttpResponse response = mHttpClient.execute(post);
                    if (response.getStatusLine().getStatusCode() == 200) {
                        mInputStream = response.getEntity().getContent();
                        String str = "";
                        String state = "";
                        BufferedReader br = new BufferedReader(
                                new InputStreamReader(mInputStream));
                        String readLine = null;
                        while ((readLine = br.readLine()) != null) {
                            // response = br.readLine();
                            str = str + readLine;
                        }
                        parseLongTermJson(str);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    mHttpClient.getConnectionManager().shutdown();
                    if (mInputStream != null) {
                        try {
                            mInputStream.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }

            }
        }.start();
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();

        finish();

    }
}
